package com.apestech.api.query;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.dictionary.modul.ImportedKey;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.DateUtil;
import com.apestech.framework.util.StringUtil;
import com.apestech.framework.util.callback.SpiltStrCallback;

import java.util.ArrayList;
import java.util.Locale;

public class TableSaveCheck extends StringUtil {

    public class ErrorField{
        private String id;
        private String value;

        public ErrorField(String id, String value) {
            this.id=id;
            this.value=value;
        }

        public String getId() {
            return id;
        }

        public String getValue() {
            return value;
        }
    }

    private SqlSession session;
    private String tableName;
    private Table table;
    private JSONObject head;
    private String type="table";
    private ArrayList<ErrorField> dfieldlist;
    private ArrayList<ErrorField> mfieldlist;
    private ArrayList<ErrorField> ifieldlist;
    private String unique;

    public TableSaveCheck(SqlSession session, String tableName) throws Exception {
        this.session=session;
        this.tableName=tableName.trim();
        dfieldlist=new ArrayList<ErrorField>();
        mfieldlist=new ArrayList<ErrorField>();
        ifieldlist=new ArrayList<ErrorField>();
        initTable();
    }

    public void checkBaseData(JSONObject row) throws Exception {
        dfieldlist.clear();
        mfieldlist.clear();
        ifieldlist.clear();
        if(row==null){
            throw new Exception("请检查，操作数据为空！");
        }
        if(unique!=null){
            final String[] msg = {""};
            execSplitStr(unique, ",", new SpiltStrCallback() {
                @Override
                public void exec(String id) throws Exception {
                    id=id.trim();
                    if(!"".equals(id) && !"IMP_STATE".equals(id)){
                        if(row.get(id)==null){
                            msg[0] = msg[0] +head.getString(id) +"不能为空;";
                        }
                    }
                }
            });
            if(!"".equals(msg[0])){
                throw new Exception(msg[0]);
            }
        }
        final String[] efield = {""};
        if(table.getDateColumn()!=null){
            execSplitStr(table.getDateColumn(),",", new SpiltStrCallback(){
                @Override
                public void exec(String id) throws Exception {
                    Object value=row.get(id);
                    if(value instanceof String && !"SYSDATE".equals(value)){
                        try{
                            String sdate=(String)value;
                            DateUtil.strToDate(sdate);
                            String s=sdate.substring(0,sdate.indexOf("-"));
                            if(s.length()>4){
                                throw new Exception(s);
                            }
                        } catch (Exception e){
                            if(!"".equals(efield[0])){
                                efield[0] = efield[0] +",";
                            }
                            efield[0] = efield[0] +id;
                            dfieldlist.add(new ErrorField(id,(String)value));
                        }
                    }
                }
            });
        }
        if(table.getNumColumn()!=null){
            execSplitStr(table.getNumColumn(),",", new SpiltStrCallback(){
                @Override
                public void exec(String id) throws Exception {
                    Object value=row.get(id);
                    if(value instanceof String){
                        if(!isNumber((String)value)){
                            if(!"".equals(efield[0])){
                                efield[0] = efield[0] +",";
                            }
                            efield[0] = efield[0] +id;
                            mfieldlist.add(new ErrorField(id,(String)value));
                        }
                    }
                }
            });
        }
        if(table.getIntColumn()!=null){
            execSplitStr(table.getIntColumn(),",", new SpiltStrCallback(){
                @Override
                public void exec(String id) throws Exception {
                    Object value=row.get(id);
                    if(value instanceof String){
                        if(!isPureDigital((String)value)){
                            if(!"".equals(efield[0])){
                                efield[0] = efield[0] +",";
                            }
                            efield[0] = efield[0] +id;
                            ifieldlist.add(new ErrorField(id,(String)value));
                        }
                    }
                }
            });
        }
        if(!"".equals(efield[0])){
            throw new Exception("["+efield[0]+"]");
        }
    }

    private String getDetailMsg(ArrayList<ErrorField> list, String msg){
        String dmsg="";
        int len=list.size();
        for(int i=0; i<len; i++){
            ErrorField f=list.get(i);
            String fid=f.getId();
            String value=f.getValue();
            String fid1=head.getString(fid);
            if(fid1!=null){
                fid=fid1;
            }
            if(!"".equals(dmsg)) dmsg=dmsg+",";
            dmsg=dmsg+fid+"("+value+")";
        }
        if(!"".equals(dmsg)){
            dmsg="["+dmsg+"]"+msg+"; ";
        } else dmsg="";
        return dmsg;
    }

    public String getErrorMsg(){
        String dmsg=getDetailMsg(dfieldlist, "格式有误，应为日期！");
        String mmsg=getDetailMsg(mfieldlist, "格式有误，应为数值！");
        String imsg=getDetailMsg(ifieldlist, "格式有误，应为整数！");
        return dmsg+mmsg+imsg;
    }

    public String getDBMsg(String msg, JSONObject map) throws Exception {
        if(msg.indexOf("ORA-00001")>=0){
            if(table.getIndex()==null){  //&& !"sql".equals(type)
                table.setIndex(session.getForDDL().getIndexInfo(tableName));
            }
            final String[] rmsg = {""};
            ArrayList<String> klist=table.getIndex().getKeylist();
            int len=klist.size();
            for(int i=0; i<len; i++){
                if(msg.indexOf(klist.get(i))>=0){
                    String COLUMN_NAME=table.getIndex().getString(klist.get(i));
                    execSplitStr(COLUMN_NAME,",", new SpiltStrCallback(){
                        @Override
                        public void exec(String id) throws Exception {
                              if(!"IMP_ID".equals(id) && !"IMP_STATE".equals(id)){
                                String sid=head.getString(id);
                                if(sid==null){
                                    sid=id;
                                }
                                if(!"".equals(rmsg[0])){
                                    rmsg[0] = rmsg[0] +",";
                                }
                                rmsg[0] = rmsg[0] +sid;
                            }
                        }
                    });
                    msg=rmsg[0]+"这几项数据存在重复数据，请检查！";
                    break;
                }
            }
        } else if(msg.indexOf("ORA-02291")>=0) {
            String id = msg.substring(msg.indexOf(".")+1, msg.indexOf(")"));
            ImportedKey imkey=table.getPkFKey();
            JSONObject m=imkey.getField();
            ArrayList<String> mlist=m.getKeylist();
            int len=mlist.size();
            for(int i=0; i<len; i++){
                ImportedKey.ImportedField impf=imkey.get(mlist.get(i));
                if(impf.getFkeyName().equals(id)){
                    String fields=impf.getColumnName();
                    //msg="["+table.getRemarks(fields)+":"+map.getString(fields)+"]没有找到符合它的基础定义错误，请检查下数据！";
                    msg=null;
                    String index_error=map.getString("index_error");
                    if(index_error==null) {
                        index_error=table.getRemarks(fields)+":"+map.getString(fields);
                    }
                    else {
                        index_error=index_error+","+table.getRemarks(fields)+":"+map.getString(fields);
                    }
                    map.put("index_error",index_error);
                    map.remove(fields);
                    break;
                }
            }
        }
        return msg;
    }

    public void setHead(JSONObject head) {
        if(head==null) this.head=null;
        else {
          this.head=new JSONObject();
          ArrayList<String> klist=head.getKeylist();
          int len=klist.size();
          for(int i=0; i<len; i++){
              String k=klist.get(i);
              this.head.put(head.getString(k), k);
          }
        }
    }

    public ArrayList<ErrorField> getDfieldlist() {
        return dfieldlist;
    }

    public ArrayList<ErrorField> getMfieldlist() {
        return mfieldlist;
    }

    public ArrayList<ErrorField> getIfieldlist() {
        return ifieldlist;
    }

    private void initTable() throws Exception {
        if(tableName.indexOf(" ")>0){
            type="sql";
            table=session.getSqlTable(tableName);
        } else {
            table=session.getDictTable(tableName);
        }
        JSONObject inx=session.getForDDL().getIndexInfo(tableName);
        unique="";
        for (String key : inx.getKeylist()){
            if(table.getPkKey()!=null && !key.equals(table.getPkKey().getPkName())){
                unique=inx.getString(key);
                break;
            }
        }
    }
}
